<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="属性名称" prop="fieldName">
            <el-input v-model="form.fieldName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="信息类型" prop="infoType">
            <el-select v-model="form.fieldValueType" filterable placeholder="请选择" prop="fieldValueType">
              <el-option
                v-for="item in valueTypeOptions"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.fieldValueType === 0" label="属性值" prop="fieldValue">
            <el-input v-model="form.fieldValue" style="width: 370px;" />
          </el-form-item>
          <el-form-item v-if="form.fieldValueType === 1" label="图片" prop="fieldValue">
            <el-upload
              ref="upload"
              :action="minioSingleFileUploadApi"
              list-type="picture-card"
              :limit="1"
              :before-upload="beforeUpload"
              :auto-upload="true"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-remove="handleRemove"
              :file-list="fileList"
            >
              <i class="el-icon-plus" />
              <div slot="tip" class="el-upload__tip">请上传图片文件,只允许上传一张图片</div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model="form.sequence" style="width: 370px;" onkeyup="value=value.replace(/[^\d]/g,'')" placeholder="请输入数字" />
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="form.valid">
              <el-radio
                v-for="item in dict.is_valid"
                :key="item.id"
                :label="item.value"
              >{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="fieldName" label="属性名称" />
        <el-table-column prop="fieldValueTypeStr" label="属性类型" />
        <el-table-column label="属性值">
          <template slot-scope="scope">
            <template v-if="scope.row.fieldValueType === 0">
              {{ scope.row.fieldValue }}
            </template>
            <template v-if="scope.row.fieldValueType === 1">
              <el-image
                :src="scope.row.fieldValue"
                :preview-src-list="[scope.row.fieldValue]"
                fit="contain"
                lazy
                class="el-avatar"
              >
                <div slot="error">
                  <i class="el-icon-document" />
                </div>
              </el-image>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="sequence" label="排序" />
        <el-table-column label="状态" align="center" prop="valid">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.valid"
              active-color="#409EFF"
              inactive-color="#F56C6C"
              @change="changeEnabled(scope.row, scope.row.valid)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="createBy" label="创建者" />
        <el-table-column v-if="checkPer(['admin','palmHallBaseInfo:edit','palmHallBaseInfo:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudPalmHallBaseInfo from '@/api/palmHallBaseInfo'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'

const defaultForm = { id: null, fieldName: null, fieldValue: null, fieldValueType: 0, fieldValueTypeStr: '文字', description: null, sequence: null, valid: 'true', createTime: null, updateTime: null, createBy: null, updateBy: null }
export default {
  name: 'PalmHallBaseInfo',
  // eslint-disable-next-line vue/no-unused-components
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['is_valid'],
  cruds() {
    return CRUD({ title: '掌上大厅基础信息配置', url: 'api/palmHallBaseInfo', idField: 'id', sort: 'id,desc', crudMethod: { ...crudPalmHallBaseInfo }})
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      fileList: [],
      valueTypeOptions: [{
        value: 0,
        label: '文字'
      },
      {
        value: 1,
        label: '图片'
      }],
      permission: {
        add: ['admin', 'palmHallBaseInfo:add'],
        edit: ['admin', 'palmHallBaseInfo:edit'],
        del: ['admin', 'palmHallBaseInfo:del']
      },
      rules: {
        fieldValueType: [
          { required: true, message: '请选择属性类型', trigger: 'blur' }
        ],
        fieldName: [
          { required: true, message: '属性名称不能为空', trigger: 'blur' }
        ],
        fieldValue: [
          { required: true, message: '属性值不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'minioSingleFileUploadApi'
    ])
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 编辑之前做的操作
    [CRUD.HOOK.beforeToEdit](crud, form) {
      form.valid = form.valid.toString()
      this.fileList = []
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToEdit](crud, form) {
      const _fileList = []
      form.fieldValueType && _fileList.push({ url: form.fieldValue })
      this.fileList = _fileList
    },
    [CRUD.HOOK.afterEditCancel](crud, form) {
      this.fileList = []
    },
    [CRUD.HOOK.beforeSubmit](crud, form) {
      this.fileList = []
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm('此操作将禁用该条数据' + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudPalmHallBaseInfo.edit(data).then(res => {
          this.crud.notify('操作成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.valid = !data.valid
        })
      }).catch(() => {
        data.valid = !data.valid
      })
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      return isLt2M
    },
    handleSuccess(response, file, fileList) {
      if (response.success) {
        this.form.fieldValue = response.fileUrl
        this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      } else {
        this.$notify({
          title: response.errMsg,
          type: 'error',
          duration: 2500
        })
      }
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    handleRemove(file, fileList) {
      this.form.fieldValue = ''
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>

<style scoped>

</style>
